package com.yang.qqclient.service;

import com.yang.common.Message;
import com.yang.common.MessageType;

import java.io.*;
import java.net.Socket;
import java.util.Date;

/**
 * @Description: 文件传输服务类
 * @Author: YANG QIANG
 * @Time: 2022-12-21 21:47
 */
public class FileClientService {

    // 一对一发送文件
    public void sendFileToOne(String src, String dest, String sender, String getter){
        FileInputStream fileInputStream = null;
        try {
            // 读取磁盘文件
            byte[] bt = new byte[(int) new File(src).length()];

            fileInputStream = new FileInputStream(src);
            fileInputStream.read(bt);

            // 构建message对象
            Message message = new Message();
            message.setMessageType(MessageType.MESSAGE_FILE_MES);
            message.setGetter(getter);
            message.setSendTime(new Date().toString());
            message.setSender(sender);
            message.setFileDestPath(dest);
            message.setFileSrcPath(src);
            message.setFileBytes(bt);
            message.setFileLen(bt.length);

            System.out.println("\n" + sender + "给" + getter + "发送文件");

            // 通过发送者的socket通道发送给服务器
            Socket socket = ManageClientConnectServerThread.getClientConnectServerThread(sender).getSocket();
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(message);

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

}
